package com.avocado.base.validator.resources;

import com.avocado.base.repository.ResourcesRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Slf4j
public class ResourcesEditCodeValidator implements ConstraintValidator<ResourcesEditCodeValidation, Object> {
    private String field1;
    private String field2;

    private final ResourcesRepository resourcesRepository;

    public ResourcesEditCodeValidator(ResourcesRepository resourcesRepository) {
        this.resourcesRepository = resourcesRepository;
    }


    @Override
    public void initialize(ResourcesEditCodeValidation constraintAnnotation) {
        this.field1 = constraintAnnotation.field1();
        this.field2 = constraintAnnotation.field2();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {


        try {

            Object field1Value = PropertyUtils.getProperty(value, field1);

            Object field2Value = PropertyUtils.getProperty(value, field2);

            Long id=(Long)field1Value;

            String code=(String)field2Value;
            //可以为空，但不能已经存在的
            if(StringUtils.isEmpty(code)||StringUtils.isBlank(code)){
                return Boolean.TRUE;
            }

            long count=resourcesRepository.getCountByCodeAndExcludeId(code,id);

            return count<1L;

        } catch (Exception ex) {
            log.error(ex.getLocalizedMessage());
        }
        return false;
    }
}
